/**
 * 2016，thor.com，all rights reserved。
 * 
 * Project：		palmmall-core
 * Filename：	AMediaServiceImpl.java
 * Created：		2016年9月18日
 * Creator：		wolv
 */
package com.thor.palmmall.rest.media;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import org.apache.cxf.jaxrs.ext.multipart.Attachment;
import org.springframework.beans.factory.annotation.Autowired;

import com.thor.commons.exception.ThorServiceException;
import com.thor.palmmall.rest.common.AAttachment;
import com.thor.palmmall.spi.common.SResponse;
import com.thor.palmmall.spi.media.SMediaService;

/**
 * @author wolv
 *
 */
public class AMediaServiceImpl implements AMediaService {

  @Override
  public AAttachment upload(Attachment attachment) throws ThorServiceException {
    AAttachment result = build(attachment);

    SResponse<String> resp = sMediaService.upload(attachment);
    if (resp.isSuccess() == false)
      throw new ThorServiceException("无法上传文件：" + resp.getMessage());

    result.setId(resp.getBody());

    return result;
  }

  @Override
  public List<AAttachment> uploadList(List<Attachment> attachments) throws ThorServiceException {
    List<AAttachment> result = new ArrayList<AAttachment>();

    for (Attachment attachment : attachments) {
      result.add(upload(attachment));
    }
    return result;
  }

  private AAttachment build(Attachment attachment) throws ThorServiceException {
    AAttachment result = new AAttachment();
    result.setName(attachment.getDataHandler().getName());
    try {
      result.setSize(attachment.getDataHandler().getInputStream().available());
    } catch (IOException e) {
    }

    return result;
  }

  @Override
  public String fileget(String fileID) throws ThorServiceException {
    SResponse<String> response = sMediaService.get(fileID);
    if (response.isSuccess() == false) {
      throw new ThorServiceException("文件获取失败：" + response.getMessage());
    }
    return response.getBody();
  }

  @Autowired
  private SMediaService sMediaService;

}
